<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\File;
use App\Schema\FileSchema;
use App\Service\SubService\UserAuth;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;
use League\Flysystem\Filesystem;

use function env;

class FileService extends Service
{
    #[Inject]
    protected Filesystem $filesystem;

    public function create(string $storage, UploadedFile $file, UserAuth $auth) :FileSchema
    {
        $allowArray = explode(',', env('ALLOW_UPLOAD_EXT'));

        $filename = $file->getClientFilename();
        $file_ext = strtolower($file->getExtension());

        if (! in_array($file_ext, $allowArray)) {
            var_dump($file_ext);
            throw new BusinessException(ErrorCode::DATA_INVALID);
        }

        $stream = fopen($file->getRealPath(), 'r+');
        $newFileName = '/uploads/' . date('Ymd') . '-' . md5((string) time()) . '.' . $file_ext;
        $this->filesystem->writeStream(
            $newFileName,
            $stream
        );

        fclose($stream);

        $model = new File();
        $model->storage = $storage;
        $model->filename = $filename;
        $model->path = $newFileName;
        $model->upload_user = $auth->getUserId();
        $model->save();

        return new FileSchema($model);
    }
}
